package controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import model.container.edges.*;
import model.container.vertices.*;
import controller.algo.*;
import controller.reader.FromFile;

/**
 * Main controller
 */
public class Main {

	/**
	 * @param args filename or directory to parse
	 */
	public static void main(String[] args) {
		long time;
		File[] files = {null};
		FromFile f = new FromFile();
		Edges edges = new TasBinaireMinimal();
		AdjacencyList vertices = new AdjacencyList();
		
		// CHANGEME
		Algo algo = new Prim();

		if(args.length < 1) {
			System.out.println("[-] Usage : Main.java [directory|file]");
			return;
		}

		try {
			FileWriter fw = new FileWriter("/tmp/out.csv");
			BufferedWriter bw = new BufferedWriter(fw);
			
			bw.write("Nb Instances, Time (ns),\n");
		
			File dir = new File(args[0]);
			if(dir.isFile())
				files[0] = dir;
			else
				files = dir.listFiles();

			for(File c : files) {
				System.out.println("Main [+] Reading "+c);
				time = System.nanoTime();
				f.fetch(c.getAbsolutePath());
				f.fillModel(vertices, edges);
				algo.loadEdges(edges);
				algo.loadVertices(vertices);
				System.out.println("Main [+] Processing ...");
				if(!algo.process())
					System.out.println("Main [-] Aborted: Error has occured !");
				bw.write(f.getNbNodes()+", "+(System.nanoTime()-time)+",\n");
				bw.flush();
				System.out.println("Took : "+(System.nanoTime()-time)+" ns");
				System.out.println("Cost : "+algo.getCost());
				System.out.println("Edges : "+algo.getNewEdges());
			}
		
			bw.close();
			System.out.println("Main [+] Written in /tmp/out.csv");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
